const Model = require('./index')

class CircleModel extends Model {
  /**
   * 分页查询友圈列表
   * @param {*} pageNo
   * @param {*} pageSize
   * @param {*} conditions
   * @returns
   */
  async findPage ({ pageNo, pageSize, conditions }) {
    const conditionSql = this.generateWhereClauseOR(conditions)
    const sql = `select sc.*, user.nickname, 
      (select count(*) from user_agree_sharecircle uas where uas.circleId = sc.id) as likeCounts,
      (select count(*) from sharecircle_comment scc where scc.circleId = sc.id) as commentCounts from share_circle sc
      left join user on user.id = sc.userId ${conditionSql} 
      order by sc.createTime desc
      limit ${pageSize} offset ${(pageNo - 1) * pageSize}`
    try {
      const list = await this.db.query(sql)
      const total = await this.total(conditionSql)
      return {
        list,
        total
      }
    } catch (error) {
      throw new Error(error)
    }
  }

  /**
   * 获取友圈总数量
   * @param {*} conditionSql
   * @returns
   */
  async total (conditionSql) {
    const sql = `select count(*) as total from share_circle sc left join user on user.id = sc.userId ${conditionSql}`
    try {
      const total = await this.db.query(sql)
      return total[0].total
    } catch (error) {
      throw new Error(error)
    }
  }

  /**
   * 根据id删除友圈，以及友圈下的点赞和评论
   * @param {*} circleId
   */
  async delete (circleId) {
    const sql = `delete sc, scc, uas from share_circle sc
      left join sharecircle_comment scc on scc.circleId = sc.id
      left join user_agree_sharecircle uas on uas.circleId = sc.id
      where sc.id = ?`
    try {
      await this.db.query(sql, [circleId])
    } catch (error) {
      throw new Error(error)
    }
  }
}

module.exports = new CircleModel('share_circle')
